package bll

import (
	"context"
	log "manager/collector/logger"
	"manager/errors"

	"manager/event"
	"manager/model"
	"manager/model/entity"
	"manager/store"
	"manager/store/postgres"
	"time"
)

type firmware struct {
	iFirmware        store.IFirmware
	iFirmwaresTactic store.IFirmwaresTactic
}

var Firmware = &firmware{
	iFirmware:        postgres.Firmware,
	iFirmwaresTactic: postgres.FirmwaresTactic,
}

func (a *firmware) init() func() {
	return func() {}
}

func (a *firmware) onEvent(*event.Data) {}

// Create 创建
func (a *firmware) Create(ctx context.Context, in *model.FirmwareCreateRequest) error {
	var (
		err error
	)

	// 构建创建现场数据
	c := buildFirmware(in)
	_, err = a.iFirmware.Create(ctx, c)
	return err
}

// Update 更新
func (a *firmware) Update(ctx context.Context, in *model.FirmwareUpdateRequest) error {
	var (
		dict = make(map[string]interface{})
	)

	updateAt := time.Now().Unix()
	in.UpdatedAt = &updateAt
	
	if in.EbikeTypeId != nil {
		dict["ebike_type_id"] = in.EbikeTypeId
	}

	if in.EbikeType != nil {
		dict["ebike_type"] = in.EbikeType
	}

	if in.Name != nil {
		dict["name"] = in.Name
	}

	if in.Version != nil {
		dict["version"] = in.Version
	}

	if in.Path != nil {
		dict["path"] = in.Path
	}

	if in.ExecStatus != nil {
		dict["exec_status"] = in.ExecStatus
	}

	if in.Desc != nil {
		dict["desc"] = in.Desc
	}

	if in.UpdatedAt != nil {
		dict["updated_at"] = in.UpdatedAt
	}

	// do other update here
	return a.iFirmware.Update(ctx, in.Id, dict)
}

// Delete 删除
func (a *firmware) Delete(ctx context.Context, in *model.FirmwareDeleteRequest) error {
	cnt, err := a.iFirmwaresTactic.CheckExistFirmwareTactic(in.Id)
	if err != nil {
		log.Error(err)
		return err
	}
	if cnt > 0 {
		return errors.FirmwareNotAllowedToDelete.Error()
	}
	return a.iFirmware.Delete(ctx, in.Id)
}

// List 列表查询
func (a *firmware) List(ctx context.Context, in *model.FirmwareListRequest) (*model.FirmwareListResponse, error) {
	var (
		err   error
		total int
		list  []*entity.Firmware
		out   = &model.FirmwareListResponse{}
	)

	if total, list, err = a.iFirmware.List(ctx, in); err != nil {
		return nil, err
	}

	out.Total = total
	out.List = model.FirmwaresEntityToDto(list)

	return out, nil
}

// Find 列表查询
func (a *firmware) Find(ctx context.Context, in *model.FirmwareInfoRequest) (*model.FirmwareInfo, error) {
	var (
		err  error
		data *entity.Firmware
		out  = &model.FirmwareInfo{}
	)

	if data, err = a.iFirmware.Find(ctx, in); err != nil {
		return nil, err
	}

	out = model.FirmwareEntityToDto(data)
	return out, nil
}

// buildFirmware 构建创建数据现场
func buildFirmware(in *model.FirmwareCreateRequest) *entity.Firmware {
	// todo: check the entity is required
	return &entity.Firmware{

		EbikeTypeId: in.EbikeTypeId,

		EbikeType: in.EbikeType,

		Name: in.Name,

		Version: in.Version,

		Path: in.Path,

		ExecStatus: in.ExecStatus,

		Desc: in.Desc,

		CreatedAt: time.Now().Unix(),

		UpdatedAt: time.Now().Unix(),
	}
}
